﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Dicom.Network.Client;
using Dicom.Network;
using Dicom.Data;
using System.Threading;
using DicomScu.Scu;
using DicomScu;
namespace WindowsFormsApplication9
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public ScuConfigDestinationCollection distination = new ScuConfigDestinationCollection();
        ScuConfig configdefaul = new ScuConfig();
        private void Form1_Load(object sender, EventArgs e)
        {
            btxconfig.Enabled = false;
            btxtmove.Enabled = false;
            groupBox1.Visible = false;
            configdefaul.LocalAE = "localhost";
            configdefaul.RemoteAE = "test";
            configdefaul.RemoteHost = "127.0.0.1";
            configdefaul.RemotePort = 4567;
            distination.ConfigCollection.Add(configdefaul);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            string msg = "";
            CEchoClient client = new CEchoClient();
            client.CalledAE = "CONQUESTSRV1";
            client.CallingAE = "vanhung";
            client.ConnectTimeout = 20;
            client.DimseTimeout = 20;
            client.MaxPduSize = Convert.ToUInt16(29);
            client.OnCEchoResponse += delegate(byte presentationID, ushort messageID, DcmStatus status)
            {
                msg = status.Description;
            };
            client.Connect("192.168.1.4", 5678, DcmSocketType.TCP);
            if (client.Wait()==true)
            {
                listBox1.Items.Add(msg);
            }
            else
            {
                listBox1.Items.Add("error");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        { 
            //CFindClient _find = new CFindClient();
           // Thread th = new Thread(new ThreadStart(connect));
            //th.Start();
           
            //th.Join();
            listView1.Items.Clear();
            object s = new object();
            CFindClient client=new CFindClient();
            client.CalledAE = "CONQUESTSRV1";
            client.CallingAE = "CONQUESTSRV1";
            
            client.ConnectTimeout = 20;
            client.DimseTimeout = 20;
            client.MaxPduSize = Convert.ToUInt16(29);
            client.SocketTimeout = 30;
            client.Priority = DcmPriority.High;
           ThreadPool.QueueUserWorkItem(new WaitCallback(connect),client);
           // client.Connect("127.0.0.1", 5678, DcmSocketType.TCP);
            CFindStudyQuery query = new CFindStudyQuery();
            query.PatientID = null;
            query.PatientsName = null;
            query.AccessionNumber = null;
            DcmDataset data = query.ToDataset(DcmTS.DeflatedExplicitVRLittleEndian);
            client.OnCFindResponse = delegate(DcmDataset querys, DcmDataset result)
            {
                //MessageBox.Show("dfdfdfd");
                laythongtin(result);

            };
            client.AddQuery(data);
           // client.Connect("127.0.0.1", 5678, DcmSocketType.TCP);
            
               
           

           
            
        }
        //public List<PatientInfo> list = new List<PatientInfo>();
        private void laythongtin(DcmDataset result)
        {
            CFindStudyQuery find = new CFindStudyQuery();
            CMoveQuery move = new CMoveQuery();
            find.AccessionNumber = getthongtin_bytab(result, DcmTags.AccessionNumber);
            find.ModalitiesInStudy = getthongtin_bytab(result, DcmTags.ModalitiesInStudy);
            find.PatientID = getthongtin_bytab(result, DcmTags.PatientID);
            find.PatientsName = getthongtin_bytab(result, DcmTags.PatientsName);
            find.StudyDescription = getthongtin_bytab(result, DcmTags.StudyDescription);
            find.StudyID = getthongtin_bytab(result, DcmTags.StudyID);
            find.StudyInstanceUID = getthongtin_bytab(result, DcmTags.StudyInstanceUID);
            
            
            
                try
                {
                    addtolistview(find);
                }
                catch (System.Exception ex)
                {
                    throw ex;
                }
            
           
        }
        public delegate  void invokelistview(CFindStudyQuery find);
        private void addtolistview(CFindStudyQuery find)
        {
           if (listView1.InvokeRequired==true)
           {
               invokelistview invoke = new invokelistview(kiemtra);
               this.Invoke(invoke,new object[]{find});
           }

           
        }
        private void kiemtra(CFindStudyQuery patient)
        {
           // listView1.Items.Clear();
            
            ListViewItem item = new ListViewItem(patient.PatientID);
            item.SubItems.Add(patient.PatientsName);
            item.SubItems.Add(patient.AccessionNumber);
            item.Tag = patient;
            listView1.Items.Add(item);
            
        }
        private string getthongtin_bytab(DcmDataset dcmdataset, DcmTag dcmtag)
        {
            DcmElement element = dcmdataset.GetElement(dcmtag);
            if (element.GetValueString()!=null)
            {
                return element.GetValueString();
            }
            else
            {
                return "";
            }
        }
        private void connect(object s)
        {
            CFindClient client =(CFindClient)s;
           
            client.Connect("192.168.1.4", 5678, DcmSocketType.TCP);
            
           
            if (client.Wait()==true)
            {
               // MessageBox.Show("error");
               
            }
        }
        private void connect_move(object s)
        {
            CMoveClient client = (CMoveClient)s;

            client.Connect("192.168.1.4", 5678, DcmSocketType.TCP);


            if (client.Wait() == true)
            {
                // MessageBox.Show("error");

            }
        }
        private void spatientinfor(DcmDataset dcm)
        {
            
            //DcmItem item = new DcmItem(DcmTags.PatientID, DcmVR.AE);
        }
        private CFindStudyQuery client_gui;
        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count>0)
            {
                btxconfig.Enabled = true;
                foreach (ListViewItem item in listView1.SelectedItems)
                {
                     client_gui = (CFindStudyQuery)item.Tag;
                }
            }
            else
            {
                btxtmove.Enabled = false;
            }
    
        }

        private void button3_Click(object sender, EventArgs e)
        {
            cstore ht = new cstore();
            ht.ShowDialog();
           // this.Close();
           
        }

        private void button4_Click(object sender, EventArgs e)
        {
           try
           {
               CMoveClient client = new CMoveClient();
               client.CalledAE = "CONQUESTSRV1";
               client.CallingAE = "vanhung";
               client.ConnectTimeout = 10;
               client.MaxPduSize = Convert.ToUInt16(30);
               client.SocketTimeout = 30;
               client.Priority = DcmPriority.High;
               client.DestinationAE =configdefaul.RemoteAE;
              
               ThreadPool.QueueUserWorkItem(new WaitCallback(connect_move), client);
               client.AddQuery(DcmQueryRetrieveLevel.Study, client_gui.AccessionNumber);
               
               client.OnCMoveResponse = delegate(CMoveQuery query, DcmDataset dataset, DcmStatus status, ushort remain, ushort complete, ushort warning, ushort failure)
               {
                   MessageBox.Show(status.State.ToString());
               };
           }
           catch (System.Exception ex)
           {
               throw ex;
           }
            
        }
        public bool move = false;
        private void button5_Click(object sender, EventArgs e)
        {
           

            if (btxconfig.Text.Contains("config")==true)
            {
                groupBox1.Visible = true;
                btxconfig.Text = "dong";
                try
                {
                    txtlocalAE.Text = configdefaul.RemoteAE;
                    txtport .Text= configdefaul.RemotePort.ToString();
                    txthost.Text = configdefaul.RemoteHost;
                  
                    //config.
                }
                catch (System.Exception ex)
                {
                	
                }
            }
            else if (btxconfig.Text=="dong")
            {
                groupBox1.Visible = false;
                btxconfig.Text = "config distination AE";
            }
        }

        private void button5_Click_1(object sender, EventArgs e)
        {
            FolderBrowserDialog dia = new FolderBrowserDialog();
            if (dia.ShowDialog()==DialogResult.OK)
            {
                textBox1.Text = dia.SelectedPath;
                distination.LocalStoreDirectoryConfig = dia.SelectedPath;
                btxtmove.Enabled = true;
            }
        }
        
    }
}
